'use strict';
const Service = require('egg').Service;
const moment = require('moment');

class MessageService extends Service {
  async index(page) {
    moment.locale('zh-cn');
    const offset_ = (page * 10) - 10;
    const allMessage = await this.app.mysql.select('message', {
      limit: 10,
      offset: offset_,
      orders: [[ 'time', 'desc' ]],
    });
    return {
      code: 200,
      data: allMessage,
    };
  }
  async sendMessage(reqObj) {
    moment.locale('zh-cn');
    const nick = reqObj.nick;
    const message = reqObj.message;
    const nowTime = moment(new Date()).format('YYYY-MM-DD LTS.ms');
    // console.log(nowTime);
    if (!nick || !message) {
      this.ctx.throw(403);
    }
    const insertMessage = await this.app.mysql.insert('message', {
      username: this.ctx.helper.escape(nick),
      msg: this.ctx.helper.escape(message),
      time: nowTime.toString(),
    });
    if (insertMessage.affectedRows === 1) {
      console.log(insertMessage);
      return {
        code: 200,
        msg: '留言发布成功',
      };
    }
  }
}

module.exports = MessageService;
